import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './assets/css/global.css'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// 导入所有Element Plus图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// Import our SafeResizeWrapper component
import SafeResizeWrapper from './components/SafeResizeWrapper.vue'

// Global patch for ResizeObserver loop limit issue
const originalResizeObserver = window.ResizeObserver;
if (originalResizeObserver) {
  // Patch the prototype to add a small delay, but in a way that doesn't block interactions
  const originalObserve = originalResizeObserver.prototype.observe;
  window.ResizeObserver.prototype.observe = function (target, options) {
    // Use requestAnimationFrame instead of setTimeout for better performance
    requestAnimationFrame(() => {
      try {
        originalObserve.call(this, target, options);
      } catch (e) {
        console.warn('ResizeObserver error suppressed:', e);
      }
    });
  };

  // Modify error handling to be less intrusive
  window.addEventListener('error', (e) => {
    if (e && e.message && e.message.includes('ResizeObserver loop limit exceeded')) {
      console.warn('ResizeObserver error intercepted globally');
      // Don't call stopPropagation or preventDefault here as it might interfere with other events
      return false; // Just log the error but let the event continue
    }
  }, true);
}

// 阻止生产环境的提示
const app = createApp(App)
app.config.productionTip = false

// 注册所有图标组件
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 配置axios
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '/api',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage中获取token
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (userInfo.token) {
      config.headers['Authorization'] = 'Bearer ' + userInfo.token
    }
    return config
  },
  error => {
    console.error(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // 如果返回的状态码不是200，说明接口请求失败
    if (res.code !== 200) {
      ElMessage.error(res.message || '系统错误')
      
      // 401: 未登录或token过期
      if (res.code === 401) {
        // 清除用户信息
        localStorage.removeItem('userInfo')
        router.replace('/login')
      }
      return Promise.reject(new Error(res.message || '系统错误'))
    } else {
      return res
    }
  },
  error => {
    console.error('请求错误', error)
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

// 添加全局方法
app.config.globalProperties.$http = service

// 日期格式化
app.config.globalProperties.$filters = {
  dateFormat(value, format = 'YYYY-MM-DD') {
    if (!value) return ''
    const date = new Date(value)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    
    if (format === 'YYYY-MM-DD') {
      return `${year}-${month}-${day}`
    } else if (format === 'YYYY年MM月DD日') {
      return `${year}年${month}月${day}日`
    } else {
      return value
    }
  }
}

// 在应用入口文件（如 main.js 或 index.js）中添加
const resizeObserverErr = window.onerror;
window.onerror = function(err, ...args) {
  if (err.includes('ResizeObserver')) {
    return false; // 阻止错误传播
  }
  return resizeObserverErr ? resizeObserverErr(err, ...args) : false;
};

// 使用插件
app.use(router)
app.use(store)
app.use(ElementPlus, { size: 'medium' })

// Register the component globally
app.component('safe-resize-wrapper', SafeResizeWrapper)

// 挂载应用
app.mount('#app')
